/*
端午节福利
BY 十一、
*/

import { Crypto, _ } from 'assets://js/lib/cat.js';

let host = '';
let hkey = '';
let playerinfos = [];
let keys = ['', '', '']; 
let cachedPlayUrls = {};
let version = '2.0.0';
let headers = {
    'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 12; PGAM10 Build/V417IR)',
    'version': '2.0.0'
};

function mockMD5(str) {
    return 'mock_' + str.replace(/[^a-zA-Z0-9]/g, '').substring(0, 32);
}

function aesDecrypt(str, keyStr, type = 'base64') {
    try {
        if (!str || !keyStr) return null;
        const key = Crypto.enc.Utf8.parse(keyStr);
        let decrypted;
        if (type === 'hex') {
            const encryptedHexStr = Crypto.enc.Hex.parse(str);
            decrypted = Crypto.AES.decrypt(
                { ciphertext: encryptedHexStr },
                key,
                { mode: Crypto.mode.ECB, padding: Crypto.pad.Pkcs7 }
            );
        } else {
            decrypted = Crypto.AES.decrypt(
                str.replace(/^\uFEFF/, '').replace(/[^A-Za-z0-9+/=]/g, ''),
                key,
                { mode: Crypto.mode.ECB, padding: Crypto.pad.Pkcs7 }
            );
        }
        return decrypted.toString(Crypto.enc.Utf8).trim() || null;
    } catch (error) {
        return null;
    }
}

function decodeBase64(str) {
    try {
        return Crypto.enc.Base64.parse(str).toString(Crypto.enc.Utf8);
    } catch (error) {
        return str;
    }
}

async function request(reqUrl, data, header, method = 'get') {
    try {
        let options = {
            method: method,
            headers: header || headers,
            timeout: 5000
        };
        if (method === 'post') {
            options.data = data || '';
            options.postType = 'form';
        }
        let res = await req(reqUrl, options);
        return res.content || '';
    } catch (error) {
        throw error;
    }
}

async function init(cfg) {
    try {
        if (!cfg.ext) throw new Error();
        let extValue = cfg.ext.trim();
        try {
            extValue = decodeBase64(extValue);
        } catch (error) {}
        
        const parts = extValue.split('|');
        host = parts[0] || '';
        keys[0] = parts[1] || '2083c87e98b6ce08';
        keys[1] = parts[2] || 'aassddwwxxllsx1x';
        version = parts[3] || '2.0.0';
        headers.version = version;

        if (!host.startsWith('http')) throw new Error();
        
        try {
            let uaResponse = await request(
                `${host}/shark/api.php?action=configs`,
                { username: '', token: '' },
                { 'User-Agent': 'okhttp/4.11.0' },
                'post'
            );
            let decrypted = aesDecrypt(uaResponse, keys[1]) || aesDecrypt(uaResponse, keys[0]);
            if (!decrypted) throw new Error();
            let cleanedResponse = decrypted.replace(/^\uFEFF/, '').replace(/<.*>/g, '').replace(/\n/g, '').trim();
            let uaData = JSON.parse(cleanedResponse);
            let uaValue = uaData.ua || uaData.config?.ua || '';
            let md5 = Crypto.MD5 || mockMD5;
            let uaPart1 = md5(uaValue).toString();
            let uaPart2 = '0000000000000000';
            let uaPart3 = md5('a.' + Math.floor(Date.now())).toString();
            headers.ua = uaPart1 + uaPart2 + uaPart3;
        } catch (error) {
            throw new Error();
        }

        let result = await getinfo();
        hkey = result[0];
        playerinfos = result[1];
        if (!hkey || !playerinfos.length) throw new Error();
    } catch (error) {
        throw new Error();
    }
}

async function getinfo() {
    try {
        let data = await request(`${host}/shark/api.php?action=configs`, { username: '', token: '' }, headers, 'post');
        let decrypted = aesDecrypt(data, keys[1]) || aesDecrypt(data, keys[0]);
        if (!decrypted) throw new Error();
        let datas = JSON.parse(decrypted);
        let hkey = (datas.config && typeof datas.config.hulue === 'string' && datas.config.hulue.split('&')[0]) || '';
        let playerinfos = datas.playerinfos || [];
        return [hkey, playerinfos];
    } catch (error) {
        return ['', []];
    }
}

async function getdata(path, method = true, data = null) {
    try {
        let url = `${host}${path}`;
        let response = method ? await request(url, '', headers) : await request(url, data, headers, 'post');
        let decrypted = aesDecrypt(response, keys[0]) || aesDecrypt(response, keys[1]);
        if (!decrypted) throw new Error();
        return JSON.parse(decrypted);
    } catch (error) {
        return { data: {} };
    }
}

async function getf(type_id) {
    try {
        let fdata = await getdata(`/api.php/v1.classify/types?type_id=${type_id}`);
        let nameObj = { type: '剧情', area: '地区', lang: '语言', year: '年份', rank: '排序' };
        let filter_list = Object.keys(fdata.data || {}).map(key => ({
            key: key.split('_')[0],
            name: nameObj[key.split('_')[0]] || key.split('_')[0],
            value: (fdata.data[key] || []).filter(j => j.type_name).map(j => ({
                n: j.type_name,
                v: j.type_name
            }))
        }));
        return [type_id, filter_list];
    } catch (error) {
        return [type_id, []];
    }
}

async function getparse(id) {
    try {
        for (let i of playerinfos) {
            if (i.playername === id) {
                return aesDecrypt(i.playerjiekou, hkey) || aesDecrypt(i.playerjiekou, keys[0]) || aesDecrypt(i.playerjiekou, keys[1]);
            }
        }
        return '';
    } catch (error) {
        return '';
    }
}

async function home(filter) {
    try {
        let cdata = await getdata('/api.php/v1.home/types');
        let classes = (cdata.data?.types || []).slice(1).map(i => ({
            type_id: i.type_id.toString(),
            type_name: i.type_name
        }));
        const promises = classes.map(i => getf(i.type_id));
        const results = await Promise.all(promises);
        let filters = {};
        for (let [type_id, filter_data] of results) {
            if (filter_data.length) filters[type_id] = filter_data;
        }
        return JSON.stringify({ class: classes, filters });
    } catch (error) {
        return JSON.stringify({ class: [], filters: {} });
    }
}

async function homeVod() {
    try {
        let data = await getdata('/api.php/v1.home/data?type_id=20');
        let vods = data.data?.banners || [];
        (data.data?.verLandList || []).forEach(item => {
            if (Array.isArray(item.vertical_lands) && item.vertical_lands.length) {
                vods = vods.concat(item.vertical_lands);
            }
        });
        return JSON.stringify({ list: vods });
    } catch (error) {
        return JSON.stringify({ list: [] });
    }
}

async function category(tid, pg, filter, extend) {
    try {
        let jsonData = {
            type_id: parseInt(tid),
            type: extend?.type || '全部类型',
            area: extend?.area || '全部地区',
            lang: extend?.lang || '全部语言',
            year: extend?.year || '全部年代',
            rank: extend?.rank || '最新',
            page: pg || 1
        };
        let data = await getdata(`/api.php/v1.classify/content`, false, jsonData);
        return JSON.stringify({
            list: data.data?.video_list || [],
            page: parseInt(pg) || 1,
            pagecount: 9999,
            limit: 9,
            total: 999999
        });
    } catch (error) {
        return JSON.stringify({
            list: [],
            page: parseInt(pg) || 1,
            pagecount: 0,
            limit: 0,
            total: 0
        });
    }
}

async function detail(ids) {
    try {
        let id = Array.isArray(ids) ? ids[0] : ids;
        let data = await getdata(`/api.php/v1.player/details?vod_id=${id}`);
        let vod = data.data?.detail;
        if (!vod) throw new Error();
        let playSources = (vod.play_url_list || []).map(i => ({
            show: i.show || 'Unknown',
            urls: i.urls.map(j => `${j.name}$${i.from}@@${j.url}`).join('#')
        }));
        const priorityMap = [
            { keyword: '4k', priority: 1 },
            { keyword: '独家', priority: 2 },
            { keyword: '秒播', priority: 3 },
            { keyword: '专线', priority: 4 },
            { keyword: '自建', priority: 5 },
            { keyword: '蓝光', priority: 6 }
        ];
        playSources.sort((a, b) => {
            const aShow = a.show.toLowerCase();
            const bShow = b.show.toLowerCase();
            const getPriority = show => {
                for (let { keyword, priority } of priorityMap) {
                    if (show.includes(keyword.toLowerCase())) {
                        return priority;
                    }
                }
                return 7;
            };
            return getPriority(aShow) - getPriority(bShow);
        });
        vod.vod_play_from = playSources.map(s => s.show).join('$$$');
        vod.vod_play_url = playSources.map(s => s.urls).join('$$$');
        vod.vod_area = `评分_${vod.vod_score || ''}`;
        vod.vod_lang = '未提供';
        delete vod.play_url_list;
        return JSON.stringify({ list: [vod] });
    } catch (error) {
        return JSON.stringify({ list: [] });
    }
}

async function search(wd, quick, pg) {
    try {
        let data = await getdata(`/api.php/v1.search/data?wd=${wd}&type_id=0&page=${pg || '1'}`);
        return JSON.stringify({
            list: data.data?.search_data || [],
            page: pg || '1'
        });
    } catch (error) {
        return JSON.stringify({ list: [], page: pg || '1' });
    }
}

async function play(flag, id, flags) {
    try {
        let [kfrom, kurl] = id.split('@@');
        let cacheKey = id;
        if (cachedPlayUrls[cacheKey]) return cachedPlayUrls[cacheKey];
        let url = '';
        let parse = 0;

        if (kfrom.toLowerCase().includes('zhibo')) {
            url = kurl;
        } else {
            let parsee = await getparse(kfrom);
            if (parsee.includes('http')) {
                let requestUrl = `${parsee}${encodeURIComponent(kurl)}`;
                let response = await request(requestUrl, '', headers);
                response = response.replace(/^\uFEFF/, '').replace(/<.*>/g, '').replace(/\n/g, '').trim();
                let data = JSON.parse(response);
                url = data.url || '';
                if (!url) throw new Error();
            } else {
                let formData = {
                    parse: parsee,
                    url: kurl,
                    matching: ''
                };
                let response = await request(
                    `${host}/shark/api.php?action=parsevod`,
                    formData,
                    { ...headers, 'Content-Type': 'application/x-www-form-urlencoded' },
                    'post'
                );
                let decrypted = aesDecrypt(response, hkey) || aesDecrypt(response, keys[0]) || aesDecrypt(response, keys[1]);
                if (!decrypted) throw new Error();
                url = JSON.parse(decrypted).url || '';
                if (!url) throw new Error();
            }
        }

        let result = JSON.stringify({ parse, url });
        cachedPlayUrls[cacheKey] = result;
        return result;
    } catch (error) {
        return JSON.stringify({ parse: 0, url: '' });
    }
}

export function __jsEvalReturn() {
    return {
        init: init,
        home: home,
        homeVod: homeVod,
        category: category,
        detail: detail,
        play: play,
        search: search
    };
}